const fs = require('fs')
const process = require('process')

function readFile(src) {
	return fs.readFileSync(src)
}

function getMacro(key) {
	return '__' + key.toUpperCase() + '__'
}

function parseSingleValue(value) {
	let output
	switch (value.type) {
		case 'file':
			output = readFile(value.src)
			break
		case 'raw':
			output = value.content
			break
	}
	output = output.toString(value.encoding)
	if (value.prefix)
		output = value.prefix + output
	if (value.suffix)
		output += value.suffix
	return output
}

function parseValue(value) {
	return value.map(parseSingleValue).join('')
}

function build(config) {
	let content = readFile(config.src).toString()
	for (let key in config.macros) {
		let macro = getMacro(key)

		let value = config.macros[key]
		let output = parseValue(value)
		content = content.replaceAll(macro, output)
	}

	fs.writeFileSync(config.dist, content)
}

let configFileName = process.argv[2]
let configString = readFile(configFileName)
let config = JSON.parse(configString)
build(config)